import React, { useEffect, useState } from 'react';
import classnames from 'classnames';
import Style from './index.module.less';
import { Input, Popup } from 'tdesign-react';
import dayjs from 'dayjs';

const RecentlyTimePicker = (props: { placeholder: string; onChange: (timestamp: number) => void; value: number }) => {
  const fillTwoDigits = (num: number) => (num < 10 ? `0${num}` : `${num}`);
  // 获取当前的时间，最近四天的日期
  const now = dayjs();
  const hour = now.hour();
  const minute = now.minute();
  const year = now.year();
  const month = now.month();
  const date = now.date();
  // console.log(hour, minute, year, month, day);
  const today = now.startOf('date');
  const tomorrow = today.add(1, 'day');
  const third = today.add(2, 'day');
  const forth = today.add(3, 'day');

  const [dateSelected, setDateSelected] = useState(today); // dateSelected: dayjs.Dayjs;
  const [hourSelected, setHourSelected] = useState(-1); // hourSelected: number, -1--23
  const [minuteSelected, setMinuteSelected] = useState(-1); // minuteSelected: number, 0,10,20,30,40,50, -1表示选择现在

  /**
   * 生成从指定小时开始到24小时的通用时间数组
   *
   * @param start 开始的小时数（0-23）
   * @returns 包含时间的数组，格式为 [{ label: string, value: number }]
   */
  const generalHours = (start: number, isToday: boolean) => {
    const tmp = Array.from({ length: 24 - start }, (val, i) => start + i);
    const res = [];
    if (isToday) res.push({ label: '现在', value: -1 }); // -1表示是现在
    tmp.forEach((item) => res.push({ label: fillTwoDigits(item), value: item }));
    return res;
  };
  /*
   * 00, 10, 20, 30, 40, 50 分钟
   * start 0, 1, 2, 3, 4, 5
   * */
  function generalMinutes(start: number) {
    const tmp = Array.from({ length: 6 - start }, (val, i) => start + i);
    const res: { label: string; value: number }[] = [];
    tmp.forEach((item) => res.push({ label: fillTwoDigits(item * 10), value: item * 10 }));
    return res;
  }
  const daysArray = [
    { label: '今天', timestamp: today.unix(), value: today },
    { label: '明天', timestamp: tomorrow.unix(), value: tomorrow },
    { label: third.format('M月D日'), timestamp: third.unix(), value: third },
    { label: forth.format('M月D日'), timestamp: forth.unix(), value: forth },
  ];

  // 第一次初始化，小时从当前小时开始，分钟不显示，从6开始
  const [hours, setHours] = useState(generalHours(minute >= 50 ? hour + 1 : hour, true));
  const [minutes, setMinutes] = useState(generalMinutes(6));

  function formatLabel() {
    if (hourSelected === -1) {
      props.onChange(now.unix());
      return '现在';
    }
    let res = '';
    daysArray.forEach((item) => {
      if (item.value.isSame(dateSelected)) {
        res += item.label;
      }
    });
    hours.forEach((item) => {
      if (item.value === hourSelected) {
        res += ` ${item.label}`;
      }
    });
    minutes.forEach((item) => {
      if (item.value === minuteSelected) {
        res += `:${item.label}`;
      }
    });
    props.onChange(dateSelected.unix() + hourSelected * 60 * 60 + minuteSelected * 60);
    return res;
  }

  const [inputValue, setInputValue] = useState<string>(formatLabel());

  const clickDay = (value: dayjs.Dayjs) => {
    // 如果是今天切到其他日期，则重置时分
    if (dateSelected.isSame(today) && !value.isSame(today)) {
      // hours 和 minutes 都要重新生成, 因为切到未来日期，所以时分都从0开始
      setHours(generalHours(0, false));
      setMinutes(generalMinutes(0));
      // 因为切到未来日期，所以时分都置0
      setHourSelected(0);
      setMinuteSelected(0);
    }
    // 如果是其他日期切到今天，则重置时分
    if (value.isSame(today) && !dateSelected.isSame(today)) {
      // hours 从当前小时开始，minutes不显示，从6开始，就会生成空数据
      setHours(generalHours(minute >= 50 ? hour + 1 : hour, true));
      setMinutes(generalMinutes(6));
      setHourSelected(-1);
      setMinuteSelected(-1);
    }
    setDateSelected(value);
  };
  const clickHour = (value: number) => {
    if (dateSelected.isSame(today)) {
      console.log('options: ', hourSelected, value);
      if (value === -1) {
        // 如果是今天，由其他小时或者现在切到现在，分要置空
        console.log('generalMinutes(6):', generalMinutes(6));
        setMinutes(generalMinutes(6));
        setMinuteSelected(-1);
        setHourSelected(value);
        setInputValue(formatLabel());
      } else if (hourSelected !== hour && value === hour) {
        // 如果是今天，由非当前小时（现在或者未来小时）切到当前小时，分要从当前分钟开始算
        const arr = generalMinutes(Math.floor(minute / 10) + 1);
        setMinutes(arr);
        setMinuteSelected(arr[0].value);
        setHourSelected(value);
      } else {
        // 如果是今天，其他情况，分要从0开始算
        setMinutes(generalMinutes(0));
        setHourSelected(value);
      }
    }
  };
  const clickMinute = (value: number) => {
    setMinuteSelected(value);
    setInputValue(formatLabel());
  };

  const panel = (
    <div className={classnames(Style.panel)}>
      <div className={classnames(Style.scroll)}>
        {daysArray.map(({ label, timestamp, value }) => (
          <div
            key={timestamp}
            className={classnames(Style.item, { [Style.itemActive]: value.isSame(dateSelected) })}
            onClick={() => clickDay(value)}
          >
            {label}
          </div>
        ))}
      </div>
      <div className={classnames(Style.scroll)}>
        {hours.map((item) => (
          <div
            className={classnames(Style.item, { [Style.itemActive]: item.value === hourSelected })}
            key={item.label}
            onClick={() => clickHour(item.value)}
          >
            {item.label}
          </div>
        ))}
      </div>
      <div className={classnames(Style.scroll)}>
        {minutes.map((item) => (
          <div
            className={classnames(Style.item, { [Style.itemActive]: item.value === minuteSelected })}
            key={item.value}
            onClick={() => clickMinute(item.value)}
          >
            {item.label}
          </div>
        ))}
      </div>
    </div>
  );
  return (
    <Popup trigger='click' content={panel} placement='bottom-left'>
      <Input placeholder={props.placeholder || '请输入时间'} value={inputValue}></Input>
    </Popup>
  );
};

RecentlyTimePicker.displayName = 'RecentlyTimePicker';

export default RecentlyTimePicker;
